<?php

namespace app\controller;


use app\BaseController;
use app\common\Amap;
use app\common\GptService;
use app\common\QuestionService;
use app\common\UsersService;
use app\job\Task;
use app\model\Question;
use app\model\QuestionAnswer;
use app\model\QuestionAnswerComment;
use app\model\QuestionClass;
use app\model\Users;
use app\model\UsersCollect;
use app\model\UsersRelated;
use app\model\UsersShield;
use app\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\Exception;
use think\facade\Queue;
use think\response\Json;

class QuestionController extends BaseController
{
	protected array $middleware = ['Login' => [
		'except' => ['index', 'class', 'test', 'read', 'comment_list', 'detail', 'same_question', 'answer_detail'],
	]];
	
	/**
	 * 屏蔽
	 * @param Request $request
	 * @return void
	 */
	function shield(Request $request)
	{
		$id = $request->post('id/d');
		UsersShield::create([
			'users_id'=>$request->users_id,
			'pro_id'=>$id,
			'type'=>'question'
		]);
		writeJson();
	}
	
	/**
	 * 互动回答-列表
	 */
	function index(Request $request,int $class_id, string $keyword, int $search_type)
	{
		
		$shield = UsersShield::where(['users_id'=>$request->users_id,'type'=>'question'])->column('pro_id');
		
		$rows = Question::with(['users'])
			->when(!empty($class_id), function (Query $query) use ($class_id) {
				$query->where('class_id', $class_id);
			})
			->whereNotIn('id',$shield)
			->when(!empty($search_type), function (Query $query) use ($search_type) {
				switch ($search_type) {
					case 1:
						$query->where(['reght_id' => 0])->order('id', 'desc');
						break;
					case 2:
						$query->where(['reght_id' => 0])->order(['browse' => 'desc', 'answer' => 'desc', 'comment' => 'desc']);
						break;
					case 3:
						$query->where(['reght_id' => 0])->order('score', 'desc');
						break;
					case 4:
						$query->where('reght_id', '<>', 0)->order(['id' => 'desc']);
						break;
				}
			})
			->when(!empty($keyword), function (Query $query) use ($keyword) {
				$query->whereLike('title|content', '%' . $keyword . '%');
			})
			->paginate()
			->items();
		writeJson($rows);
	}
	
	/**
	 * 互动回答-回复列表
	 * @param Request $request
	 * @param int $id
	 * @return Json
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws ModelNotFoundException
	 */
	function read(Request $request, int $id): Json
	{
		event('QuestionIncBrowse', $id); //增加浏览数量
		$users_ids = QuestionAnswer::where(['question_id' => $id, ['like', '>=', 5]])->group('users_id')->column('users_id');
		if (count($users_ids) > 1) {
			//计算回复中历史帮助赞同最多的用户
			$reght = Users::whereIn('id', $users_ids)->max('reght');
			$reght = Users::whereIn('id', $users_ids)->where(['reght' => $reght])->select();
			if ($reght->count() > 1) {
				//计算谁先回答的时间
				$ids = $reght->column('id');
				$fast = QuestionAnswer::where(['question_id' => $id])->whereIn('users_id', $ids)->order(['createtime' => 'asc'])->find();
				$the_best_user_id = $fast->id;
			} else {
				$the_best_user_id = $reght[0]->id;
			}
		} elseif (count($users_ids) == 1) {
			$the_best_user_id = $users_ids[0];
		}else{
			$the_best_user_id = 0;
		}
		
		$answer = QuestionAnswer::with([
			'users',
			'users_collect' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question_answer']);
			},
			'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question_answer']);
			},
			'users_agree' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question_answer']);
			},
			'comments' => function (Query $query) {
				$query->with(['users', 'to_users'])->order(['id' => 'desc']);
			},
			'question'
		])
			->filter(function ($data) use ($the_best_user_id) {
				$data->the_best = 0;
				if (!empty($the_best_user_id) && $data->users_id == $the_best_user_id) {
					$data->the_best = 1;
				}
			})
			->where(['question_id' => $id])
			->order(['bot' => 'desc', 'id' => 'desc', 'reght' => 'desc'])
			->paginate()
			->items();
		
		writeJson(['answer' => $answer]);
	}
	
	/**
	 * 详情
	 * @param Request $request
	 * @param int $id
	 * @return Json
	 */
	function detail(Request $request, int $id)
	{
		$row = Question::with(['users', 'users_collect' => function (Query $query) use ($request) {
			$query->where(['users_id' => $request->users_id, 'type' => 'question']);
		}])->find($id);
		//软删除
		if (!$row) {
			writeJson(102, '该问题不存在');
		}
		UsersService::footmark($id, $request->users_id, 'question');
		
		writeJson($row);
	}
	
	/**
	 * 回复详情
	 * @param Request $request
	 * @param int $id
	 * @return Json
	 */
	function answer_detail(Request $request, int $id)
	{
		$res = QuestionAnswer::with([
			'users',
			'users_collect' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question_answer']);
			},
			'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question_answer']);
			},
			'users_agree' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question_answer']);
			},
			'question',
			])
			->find($id);
		UsersService::footmark($id, $request->users_id, 'question_answer');
		writeJson($res);
	}
	
	/**
	 * 相似问题
	 * @param int $id
	 * @return Json
	 */
	function same_question(int $id)
	{
		$res = Question::findOrFail($id);
		$rows = Question::whereTime('createtime','-7 day')->with(['users'])->where('id','<>',$id)->select();
		$data=[];
		$similaritys = [];
		foreach ($rows as $row){
			similar_text($row->title, $res->title, $similarity);
			if ($similarity>=50){
				$row->similarity = $similarity;
				$data[] = $row;
				$similaritys [] = $similarity;
			}
		}
		array_multisort($similaritys, SORT_DESC, $data);
		writeJson($data);
	}
	
	/**
	 * 互动回答-发布
	 */
	function save(Request $request): Json
	{
		$params = $request->param(); //type 1=全部 2=娱乐 3=教育 4=互联网
		#有积分  执行减积分
		if ($params['score'] > 0) {
			try {
				UsersService::changeScore(-$params['score'], $request->users_id, '互动问答悬赏积分');
			} catch (Exception $e) {
				writeJson(0, $e->getMessage());
			}
		}
		$QuestionrModel = new Question();
		$adopt = $QuestionrModel->where(['reght_id' => 0, 'users_id' => $request->users_id])->find();
        if ($adopt) {
	        writeJson(1,'有问题待处理',$adopt);
        }
		$QuestionrModel->save($params);
		try {
			GptService::decGptNum($request->users_id,1,$params['content']);
			Queue::push(Task::class, ['data' => ['id' => $QuestionrModel->id], 'action' => 'QuestionBot'], 'task');
		}catch (Exception $e){
			if ($e->getCode()==0){
				writeJson(0,$e->getMessage());
			}
		}
		writeJson($QuestionrModel);
	}
	
	
	/**
	 * 是否相同标题
	 * @param Request $request
	 * @return Json
	 */
	function is_same(Request $request)
	{
		$title = $request->param('title'); //
		$row = Question::whereLike('title', '%' . $title . '%')->with(['users'])->find();
		if ($row) {
			writeJson(1, '已有相似内容', $row);
		}
		writeJson(1, 'ok');
	}
	
	/**
	 * 互动回答-回复
	 * @param Request $request
	 * @return Json
	 */
	function answer(Request $request): Json
	{
		$pamars = $request->param();
		$row = QuestionService::answer($pamars);
		$res = QuestionAnswer::with(['users',
			'users_collect' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question']);
			},
			'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question']);
			},
			'users_agree' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question']);
			},
			'comments',
			'question',
		])->find($row->id);
		writeJson($res);
	}
	
	/**
	 * 互动回答-评论
	 * @param Request $request
	 * @return Json
	 */
	function comment(Request $request): Json
	{
		$params = $request->param();
		$ip = $request->ip();
		$params['ip'] = $ip;
		$ip = Amap::ip($ip);
		$ip = json_decode($ip);
		if ($ip->status == 1) {
			$params['city'] = $ip->province;
		} else {
			$params['city'] = '未知';
		}
		$answer = QuestionAnswer::findOrFail($params['answer_id']);
		$params['question_id'] = $answer->question_id;
		event('QuestionIncComment', $params['question_id']); //增加互动数量
		event('QuestionAnswerIncComment', $params['answer_id']); //增加回复的评论数量
		$res = QuestionAnswerComment::create($params);
		foreach ($params['content'] as $v) {
			if ($v['type'] == 'at') {
				//@提醒  提醒接收人
				UsersRelated::create(['users_id' => $v['userId'], 'type' => 8, 'from_users_id' => $request->users_id, 'scene' => 'QuestionAnswer', 'pro_id' => $res->id]);
			}
		}
		if (!empty($params['to_users_id'])) {
			//回复提醒  提醒接收人
			UsersRelated::create(['users_id' => $params['to_users_id'], 'type' => 1, 'from_users_id' => $request->users_id, 'scene' => 'QuestionAnswer', 'pro_id' => $res->id]);
		} else {
			//评论提醒  提醒发布人
			$pro = QuestionAnswer::find($params['answer_id']);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 2, 'from_users_id' => $request->users_id, 'scene' => 'QuestionAnswer', 'pro_id' => $res->id]);
		}
		$row = QuestionAnswerComment::with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
			$query->where(['users_id' => $request->users_id, 'type' => 'question_answer_comment']);
		}])->find($res->id);
		writeJson($row);
	}
	
	/**
	 * 评论列表
	 * @param int $answer_id
	 * @param mixed $comment_id
	 * @param Request $request
	 * @return Json
	 */
	function comment_list(int $answer_id, mixed $comment_id, Request $request): Json
	{
		$top_id = 0;
		if (!empty($comment_id)) {
			$row = QuestionAnswerComment::find($comment_id);
			if ($row->pid == 0) {
				//顶级评论 放在第一条
				$top_id = $row->id;
			} else {
				//子评论 找出顶级评论
				$row = QuestionAnswerComment::find($row->pid);
				$top_id = $row->id;
			}
		}
		
		$res = QuestionAnswerComment::where(['answer_id' => $answer_id, 'pid' => 0])
			->withCount('comment')
			->with([
				'users',
				'comment' => function (Query $query) use ($request, $comment_id) {
					$query
						->with(['users', 'to_users', 'users_like' => function (Query $query) use ($request) {
							$query->where(['users_id' => $request->users_id, 'type' => 'question_answer_comment']);
						}])
						->when(!empty($comment_id), function (Query $query) use ($comment_id) {
							$query->field("*,IF(id = $comment_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
						}, function (Query $query) {
							$query->order(['id' => 'desc']);
						})
						->limit($this->comment_list_rows);
				},
				'users_like' => function (Query $query) use ($request) {
					$query->where(['users_id' => $request->users_id, 'type' => 'question_answer_comment']);
				}])->filter(function ($data) {
			})
			->when(!empty($comment_id), function (Query $query) use ($top_id) {
				$query->field("IF(id = $top_id,1,0) AS top")->order(['top' => 'desc', 'id' => 'desc']);
			}, function (Query $query) {
				$query->order(['id' => 'desc']);
			})
			->paginate()
			->items();
		
		UsersService::footmark($answer_id, $request->users_id, 'answer');
		
		writeJson($res);
	}
	
	/**
	 * 评论详情
	 * @param int $id
	 * @param mixed $comment_id
	 * @param Request $request
	 * @return Json
	 */
	function comment_detail(int $id, mixed $comment_id, Request $request)
	{
		$child = false;
		if (!empty($comment_id)) {
			$row = QuestionAnswerComment::find($comment_id);
			if ($row->pid != 0) {
				//二级评论
				$child = true;
			}
		}
		
		$res = QuestionAnswerComment::with([
			'users',
			'to_users',
			'users_like' => function (Query $query) use ($request) {
				$query->where(['users_id' => $request->users_id, 'type' => 'question_answer_comment']);
			},
		])
			->when($child, function (Query $query) use ($comment_id) {
				$query->where('id', '<>', $comment_id);
			})
			->where(['pid' => $id])
			->order(['id' => 'desc'])
			->paginate($this->comment_detail_rows)
			->items();
		writeJson($res);
	}
	
	
	/**
	 * 评论点赞
	 * @param Request $request
	 * @return Json
	 */
	function comment_like(Request $request)
	{
		$id = $request->param('id');
		$res = UsersService::like($id, $request->users_id, 'question_answer_comment');
		$res ? event('QuestionAnswerCommentIncLike', $id) : event('QuestionAnswerCommentDecLike', $id); //增加/减少  点赞数量
		if ($res) {
			$pro = QuestionAnswerComment::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 4, 'from_users_id' => $request->users_id, 'scene' => 'QuestionAnswer', 'pro_id' => $pro->id]);
		}
		writeJson($res);
	}
	
	/**
	 * 互动问答-类目
	 * @return Json
	 */
	function class()
	{
		$QuestionClassModel = new QuestionClass();
		$res = $QuestionClassModel->select();
		writeJson($res);
	}
	
	/**
	 * 收藏问题
	 * @param Request $request
	 * @return Json
	 */
	function collect_question(Request $request)
	{
		$id = $request->post('id');
		$res = UsersService::collect($id, $request->users_id, 'question');
		if ($res) {
			$pro = Question::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 7, 'from_users_id' => $request->users_id, 'scene' => 'Question', 'pro_id' => $pro->id]);
		}
		writeJson($res);
	}
	
	/**
	 * 互动问答-收藏回复
	 * @param Request $request
	 * @return Json
	 */
	function collect(Request $request)
	{
		$id = $request->post('id');
		$res = UsersService::collect($id, $request->users_id, 'question_answer');
		$res ? event('QuestionAnswerIncCollect', $id) : event('QuestionAnswerDecCollect', $id); //增加/减少  收藏数量
		if ($res) {
			$pro = QuestionAnswer::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 7, 'from_users_id' => $request->users_id, 'scene' => 'QuestionAnswer', 'pro_id' => $pro->id]);
			$has = UsersCollect::where(['type' => 'question', 'users_id' => $request->users_id, 'pro_id' => $pro->question_id])->find();
			if (!$has) {
				UsersService::collect($pro->question_id, $request->users_id, 'question');
			}
		}
		writeJson($res);
	}
	
	
	/**
	 * 互动问答-回复点赞
	 * @param Request $request
	 * @return Json
	 */
	function like(Request $request)
	{
		$id = $request->post('id');
		$res = UsersService::like($id, $request->users_id, 'question_answer');
		$res ? event('QuestionAnswerIncLike', $id) : event('QuestionAnswerDecLike', $id); //增加/减少  点赞数量
		if ($res) {
			$pro = QuestionAnswer::find($id);
			UsersRelated::create(['users_id' => $pro->users_id, 'type' => 3, 'from_users_id' => $request->users_id, 'scene' => 'QuestionAnswer', 'pro_id' => $pro->id]);
		}
		writeJson($res);
	}
	
	
	/**
	 * 互动问答-赞同
	 * @param Request $request
	 * @return Json
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws ModelNotFoundException
	 */
	function agree(Request $request)
	{
		$id = $request->post('id');
		$row = QuestionAnswer::find($id);
		if ($row->question->reght_id != 0) {
			writeJson(0, '此问题已被采纳');
		}
		$users_id = $row->question->users_id;
		if ($users_id != $request->users_id) {
			writeJson(0, '只能题主采纳');
		}
		if ($request->users_id == $row->users_id) {
			writeJson(0, '不能采纳自己的回答');
		}
		
		$res = UsersService::agree($id, $request->users_id, 'question_answer', $row->users_id);
		if ($res) {
			$row->users->reght += 1;
		}
		$row->agree += 1;
		$row->question->reght_id = $id;
		$row->reght = 1;
		if ($row->question->score != 0) {
			try {
				UsersService::changeScore($row->question->score, $row->users_id, '互动问答采纳积分');
			} catch (Exception $e) {
				writeJson(0, $e->getMessage());
			}
		}
		//采纳通知
		UsersRelated::create(['users_id' => $row->users_id, 'type' => 9, 'from_users_id' => $request->users_id, 'scene' => 'QuestionAnswer', 'pro_id' => $id]);
		
		$row->together(['question', 'users'])->save();
		writeJson(true);
		
	}
	
	
	/**
	 * 积分悬赏
	 * @param Request $request
	 * @return Json
	 */
	function score_reward(Request $request)
	{
		$id = $request->post('id');
		$score = $request->post('score');
		$users = Users::find($request->users_id);
		if ($request->isGet()) {
			writeJson($users);
		}
		$row = Question::find($id);
		if ($row->reght_id != 0) {
			writeJson(0, '此问题已采纳');
		}
		if ($score <= 0) {
			writeJson(0, '悬赏积分不能小于0');
		}
		try {
			UsersService::changeScore(-$score, $request->users_id, '互动问答悬赏追加积分');
		} catch (Exception $e) {
			writeJson(0, $e->getMessage());
		}
		$row->score += $score;
		$row->save();
		writeJson();
	}
	
	
	/**
	 * 删除
	 * @param Request $request
	 * @return Json
	 */
	function delete(Request $request)
	{
		$id = $request->post('id/d');
		$row = Question::where(['users_id' => $request->users_id, 'id' => $id])->findOrFail();
		if ($row->reght_id != 0) {
			writeJson(0, '已采纳的问题不能下架');
		}
		$row->delete();
		writeJson();
	}
	
	/**
	 * 下架(暂时用不到)
	 * @param Request $request
	 * @return Json
	 */
	function down(Request $request)
	{
		$id = $request->post('id/d');
		$down_reason = $request->post('down_reason');
		$down_images = $request->post('down_images');
		Question::where(['id' => $id])->update(['status' => 0, 'down_reason' => $down_reason, 'down_images' => $down_images]);
		writeJson();
	}
	
	
}